package com.cloudeye.logtest.netty;

import io.netty.channel.*;
import sun.nio.ch.FileChannelImpl;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.nio.channels.WritableByteChannel;

/**
 * Created by lafangyuan on 2020/12/1.
 */
public class FileServerHandler extends SimpleChannelInboundHandler<String> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String data) throws Exception {
        RandomAccessFile raf = null;
        FileDescriptor fileDescriptor = new FileDescriptor();
//        WritableByteChannel wbc = new FileChannelImpl(fileDescriptor,"r","");
        long len = -1;
        try {
            raf = new RandomAccessFile(data,"r");
            len = raf.length();
        } catch (FileNotFoundException e) {
            ctx.writeAndFlush("ERR:"+e.getMessage());
        }finally {
            if(len<0&&raf==null){
                raf.close();
            }
        }
        ctx.write("OK: " + raf.length() + '\n');

        FileRegion fileRegion = new DefaultFileRegion(raf.getChannel(), 0, len);
        ctx.writeAndFlush(fileRegion);
    }
}
